class VouchersController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @voucher_pages, @vouchers = paginate :vouchers, :per_page => 10
  end

  def show
    @voucher = Voucher.find(params[:id])
  end

  def new
    @voucher = Voucher.new
    @cart=find_cart

  end

  def create
    @voucher = Voucher.new(params[:voucher])
    @cart=find_cart
    @voucher.line_items=@cart.items
    if @voucher.save
      flash[:notice] = 'Voucher was successfully created.'
      redirect_to :action => 'list'
      @cart.items.clear
    else
      render :action => 'new'
    end
  end

  def edit
    @voucher = Voucher.find(params[:id])
  end

  def update
    @voucher = Voucher.find(params[:id])
    if @voucher.update_attributes(params[:voucher])
      flash[:notice] = 'Voucher was successfully updated.'
      redirect_to :action => 'show', :id => @voucher
    else
      render :action => 'edit'
    end
  end

  def destroy
    Voucher.find(params[:id]).destroy
    redirect_to :action => 'list'
  end

  def create_line_item
    @line_item = LineItem.new(params[:line_item])
    @cart=find_cart
    if (@cart.add_item(@line_item))
      flash[:notice] = 'LineItem was successfully created.'
      redirect_to :action => 'new'
    else
      flash[:notice] = 'LineItem was failing.'
      redirect_to :action => 'new'
    end
  end
  def clear_line_item
    @cart=find_cart
    @cart.items.clear
    redirect_to :action => 'new'
  end


  private
  def find_cart
    session[:cart]  ||= Cart.new
  end
end
